package com.zhgxi.openfire;

import org.jivesoftware.smack.*;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.junit.Test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created with IntelliJ IDEA.
 * User: xi
 * Date: 13-12-3
 * Time: 下午4:31
 * To change this template use File | Settings | File Templates.
 */
public class AutoRegister {

    private static void reg(Connection connection, String userName, String password) throws XMPPException {
        if (!connection.isConnected()) connection.connect();

        AccountManager amgr = connection.getAccountManager();
        amgr.createAccount(userName, password);
        //更改用户状态代码：

        Presence presence = new Presence(Presence.Type.available);   //这里如果改成unavailable则会显示用户不在线
        presence.setStatus("Go fishing");
        connection.sendPacket(presence);
        connection.getRoster();
    }

    public static void main(String[] args) throws XMPPException, IOException {
        ConnectionConfiguration config = new ConnectionConfiguration("127.0.0.1", 5222);
        Connection connection = new XMPPConnection(config);
        connection.connect();
        String userName = "android7";
        String password = "111111";
        AutoRegister.reg(connection, userName, password);

        connection.login(userName, password);
        ChatManager chatManager = connection.getChatManager();
        Chat chat = chatManager.createChat("xi@xi-pc", new MessageListener() {  //这里第一个参数是接收人的地址，不能只写用户名，具体是什么可以在上面先用System.out.println(conn.getUser());把用户的具体表示方法打印出来看看
            @Override
            public void processMessage(Chat chat,
                                       Message message) {
                try {
                    chat.sendMessage("hahaha");
                } catch (XMPPException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
                System.out.println("Received message:" + message.getBody());
            }
        });

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String message = "";
        while (!(message = br.readLine()).equals("exit")) {
            System.out.println(connection.getUser() + " Please input the message:");
            chat.sendMessage(message);
        }

        connection.disconnect();
    }
}
